<template>
  <div class="temperature-chart">
    <div class="chart-header">
      <span class="city-name">{{ city }}</span>
      <div class="select-container">
        <el-input
          v-model.number="selectedYear"
          size="small"
          placeholder="请输入年份"
          type="number"
          :min="minYear"
          :max="maxYear"
          @change="validateYear"
        >
          <template #append>年</template>
        </el-input>
      </div>
    </div>
    <div class="chart-wrapper">
      <canvas ref="chartCanvas"></canvas>
      <div v-if="isLoading" class="loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        数据加载中...
      </div>
      <div v-if="error" class="error">{{ error }}</div>
      <!-- 调试信息，仅开发环境显示
      <div v-if="debugInfo" class="debug-info">
        <pre>{{ debugInfo }}</pre>
      </div> -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { 
  Chart, 
  LineElement, 
  CategoryScale, 
  LinearScale, 
  PointElement, 
  LineController, 
  TimeScale,
  Tooltip,
  Legend
} from 'chart.js';
import 'chartjs-adapter-date-fns';
import { zhCN } from 'date-fns/locale';
import { fetchTemperatureData, getYearsList } from '@/api/get_historical_temperature_data_by_year';
import { Loading } from '@element-plus/icons-vue';

// 注册所有必要的图表组件
Chart.register(
  LineElement, 
  CategoryScale, 
  LinearScale, 
  PointElement, 
  LineController, 
  TimeScale,
  Tooltip,
  Legend
);

const props = defineProps<{
  city: string;
  temperatureField: string;
}>();

const chartCanvas = ref<HTMLCanvasElement | null>(null);
const selectedYear = ref<number | null>(null);
const years = ref<number[]>([]);
const minYear = ref(2000);
const maxYear = ref(new Date().getFullYear());
const chart = ref<Chart | null>(null);
const isLoading = ref(false);
const error = ref<string | null>(null);
const debugInfo = ref<string | null>(null); // 用于调试信息

// 初始化年份列表
const initYears = async () => {
  try {
    isLoading.value = true;
    years.value = await getYearsList();
    selectedYear.value = years.value.length > 0 ? Math.max(...years.value) : maxYear.value;
  } catch (err) {
    const errorMessage = err instanceof Error ? err.message : String(err);
    error.value = '获取年份数据失败';
    console.error('获取年份数据失败:', err);
    debugInfo.value = `获取年份数据失败: ${errorMessage}`;
  } finally {
    isLoading.value = false;
  }
};

// 验证年份输入
const validateYear = () => {
  if (!selectedYear.value) {
    selectedYear.value = maxYear.value;
    return;
  }
  
  if (selectedYear.value < minYear.value) {
    selectedYear.value = minYear.value;
  } else if (selectedYear.value > maxYear.value) {
    selectedYear.value = maxYear.value;
  }
  
  updateChart();
};

// 更新图表
const updateChart = async () => {
  if (!chartCanvas.value || !selectedYear.value) return;

  try {
    isLoading.value = true;
    error.value = null;
    debugInfo.value = null;
    
    const response = await fetchTemperatureData(selectedYear.value, props.temperatureField);
    console.log('API响应:', response); // 完整输出API响应
    debugInfo.value = JSON.stringify(response, null, 2);

    if (!response || !response.data || response.data.length === 0) {
      throw new Error('没有可用的温度数据');
    }

    // 转换数据格式
    const chartData = response.data.map(item => ({
      x: new Date(item.record_date),
      y: Number(item[props.temperatureField]) // 确保转换为数字
    }));
    
    console.log('转换后的图表数据:', chartData);
    debugInfo.value += `\n\n转换后的图表数据 (${chartData.length} 条):\n${JSON.stringify(chartData.slice(0, 5), null, 2)}${chartData.length > 5 ? '...' : ''}`;

    if (chartData.length === 0) {
      throw new Error('转换后没有有效的图表数据');
    }

    // 销毁旧图表
    if (chart.value) {
      chart.value.destroy();
    }

    interface ChartDataPoint {
      x: Date;
      y: number;
    }

    // 创建新图表（移除了阴影部分）
    chart.value = new Chart<"line", ChartDataPoint[]>(chartCanvas.value.getContext('2d')!, {
      type: 'line',
      data: {
        datasets: [{
          label: `${props.city}气温 (°C)`,
          data: chartData,
          borderColor: '#1890ff',
          backgroundColor: '', // 移除阴影填充
          fill: false, // 关闭填充
          tension: 0.4,
          pointRadius: 3,
          pointHoverRadius: 5,
          borderWidth: 2
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        animation: {
          duration: 0 // 禁用动画，加快渲染
        },
        scales: {
          y: {
            min: -10,
            max: 40,
            grid: {
              color: 'rgba(0, 0, 0, 0.05)'
            },
            ticks: {
              callback: (value) => `${value}°C`
            },
            title: {
              display: true,
              text: '温度 (°C)'
            }
          },
          x: {
            type: 'time',
            time: {
              unit: 'month',
              displayFormats: {
                month: 'M月'
              },
              tooltipFormat: 'yyyy年M月d日'
            },
            adapters: {
              date: {
                locale: zhCN
              }
            },
            grid: {
              color: 'rgba(0, 0, 0, 0.05)'
            },
            ticks: {
              autoSkip: true,
              maxRotation: 45,
              minRotation: 30
            },
            title: {
              display: true,
              text: '日期'
            }
          }
        },
        plugins: {
          legend: {
            display: false
          },
          tooltip: {
            callbacks: {
              label: (ctx) => `温度: ${ctx.parsed.y}°C`,
              title: (ctx) => 
                new Date(ctx[0].parsed.x).toLocaleDateString('zh-CN', {
                  year: 'numeric',
                  month: '2-digit',
                  day: '2-digit'
                })
            }
          }
        }
      }
    });

  } catch (err: any) {
    error.value = err.message || '获取温度数据失败';
    console.error('图表渲染失败:', err);
    debugInfo.value += `\n\n错误: ${err.message}`;
    
    // 显示空状态
    if (chart.value) {
      chart.value.destroy();
      chart.value = null;
    }
  } finally {
    isLoading.value = false;
  }
};

onMounted(async () => {
  await initYears();
  updateChart();
});

watch(selectedYear, () => {
  updateChart();
});
</script>

<style scoped>
.temperature-chart {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  min-height: 0;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 8px;
  margin-bottom: 8px;
  flex-shrink: 0;
}

.city-name {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.select-container {
  display: flex;
  gap: 8px;
}

:deep(.el-input) {
  width: 120px;
}

.chart-wrapper {
  flex: 1;
  min-height: 300px;
  position: relative;
  width: 100%;
}

canvas {
  display: block;
  width: 100% !important;
  height: 100% !important;
}

.loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 10;
  gap: 8px;
}

.error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: red;
  text-align: center;
  z-index: 10;
}

/* .debug-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  max-height: 150px;
  overflow-y: auto;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  font-size: 12px;
  padding: 8px;
  z-index: 20;
  white-space: pre-wrap;
  font-family: monospace;
} */
</style>